#!/bin/bash
# Description: This shell script used to build LoRaWAN gateway program packet_forward
#
#     Author: Zhang.Kang <13874854275@163.com>
#     Version: 1.0.0  


PROJ_PATH=`pwd`
TFTP_PATH=/tftp

BOARD=K6
CROSSTOOL=/opt/buildroot/arm926t/bin/arm-linux-

lora_gateway=lora_gateway-5.0.1
packet_forwarder=packet_forwarder-4.0.1

PACK_PATH=${PROJ_PATH}/tarballs
PATCH_PATH=${PROJ_PATH}/patches 

target=

set -e

function show_banner()
{
	echo "+---------------------------------------------+" 
	printf "$1\n"
	echo "+---------------------------------------------+"
}


function do_build()
{
    SRC_DIR=$1
    PATCH_SUFIX=${BOARD}.patch

    if [ ! -d ${SRC_DIR} ] ; then
	    show_banner "|       start decompress $SRC_DIR packet     |"
        tar -xzf ${PACK_PATH}/${SRC_DIR}.tar.gz
        cd ${SRC_DIR}

        # patch for it
        ls ${PATCH_PATH}/${SRC_DIR}-${PATCH_SUFIX}
        if [ -f ${PATCH_PATH}/${SRC_DIR}-${PATCH_SUFIX} ] ; then 
            show_banner "|            patch for ${SRC_DIR}             |"
            patch -p1 < ${PATCH_PATH}/${SRC_DIR}-${PATCH_SUFIX}
        fi

    else
        cd ${SRC_DIR}
    fi

	show_banner "|   start $SRC_DIR build task...            |"
    make
	show_banner "|   $SRC_DIR build task over!               |"

    cd -
}

function do_clean()
{
    SRCS="${lora_gateway} ${packet_forwarder}"

	show_banner "|         clean project source code           |"
    
    for dir in $SRCS
    do
        if [ -d $dir ] ; then
            rm -rf ${dir}
        fi
    done
}

if [ $# == 1 ] ; then
   if [ $1 == "clean" ] ; then
      show_banner "           Cleanup source code..."
      rm -f lora_pkt_fwd
      do_clean > /dev/null
      exit 0;
   elif [ $1 == "patch" ] ; then
      show_banner "           Generate patch files..."
      ./patches/gen_patch.sh ${lora_gateway}
      ./patches/gen_patch.sh ${packet_forwarder}
      exit 0;
   fi 
fi

show_banner "|  build LoRaWAN gateway program 'packet_forward' for [$BOARD] |"

# packet_forwarder program depends on mosquitto, will build here
cd ../../3rdparty/mosquitto/
   sudo bash build.sh
cd -

do_build ${lora_gateway}
do_build ${packet_forwarder}

cp ${packet_forwarder}/lora_pkt_fwd/lora_pkt_fwd  ${PROJ_PATH}

